import { hasToken } from '@/utils/storage';
import React from 'react';
import { Route, Redirect, useHistory, RouteProps } from 'react-router-dom';

interface AuthRouteProps extends RouteProps {
  path: string;
  component: React.FC;
}

export default function AuthRoute({
  path,
  component: Component,
  ...restProps
}: AuthRouteProps) {
  const history = useHistory();
  return (
    <Route
      {...restProps}
      path={path}
      render={() => {
        if (hasToken()) {
          return <Component />;
        } else {
          return (
            <Redirect
              to={{
                pathname: '/login',
                // 通过 state 存储重定向前的页面路径，用于登录成功后回跳
                state: { from: history.location.pathname },
              }}
            />
          );
        }
      }}
    ></Route>
  );
}
